//
//  JCLNetWorkTools.swift
//  WeiBo
//
//  Created by DDC on 2017/9/9.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import AFNetworking

enum JCLNetMethod {
    case GET
    case POST
}

class JCLNetWorkTools: AFHTTPSessionManager {

    //模型
    lazy var userAccount = JCLUserAccountModel()
    //网络工具类单例
    static let shared = JCLNetWorkTools()
    
//    var uid:String? = "5365823342"
    //2.00Zzp2lB9kzLnC8f4a6dec9enS9gME  2.00Zzp2lBGCpNlB4f03a33ce903ChTx
    
    
//    var accrssToken:String? // = "2.00Zzp2lBGCpNlB55de7a7a2eiicJLD"
    
    //判断是否登录的计算型属性
    var userLogon:Bool {
        
        return userAccount.access_token != nil
    }
    //处理token
    /// 专门负责拼接token的网络封装方法
    ///
    /// - Parameters:
    ///   - method: get/ post
    ///   - URLString: urlstring
    ///   - parameters: 参数字典
    ///   - name: 上传文件使用的字段名,默认为nil,不上传文件
    ///   - data: 上传文件使用的二进制数据,默认为nil,不上传文件
    ///   - completion: 完成回调
    func requestToken(method: JCLNetMethod = .GET ,URLString: String , parameters:[String: Any]?,name:String? = nil ,data:Data? = nil ,completion:@escaping (_ json: Any?,_ isSuccess: Bool)->()) {
        
        //处理token let params = ["access_token" : "2.00Zzp2lBGCpNlB4f03a33ce903ChTx"]
        guard let token = userAccount.access_token else {
            
            print("token 不存在")
            // FIXME: 处理token 发送通知
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: JCLUserShouldLoginNotification), object: nil)
            //返回错误信息
            completion(nil,false)
            return
        }
        
        var parameters = parameters
        if parameters == nil {
            parameters = [String:Any]()
        }
        parameters!["access_token"] = token
        
        // 判断是否是上传文件
        if let name = name,let data = data {
            // 上传文件
            upload(URLString: URLString, parameters: parameters, name: name, data: data, completion: completion)
        } else {
            
            // 获取网络接口的唯一方法
            //        request(URLString: URLString, parameters: parameters!, completion: completion)
            request(method: method, URLString: URLString, parameters: parameters!, completion: completion)
        }
        
    }
    
    
    /// 用一个方法封装AFN的文件上传方法
    ///
    /// - Parameters:
    ///   - URLString: urlString
    ///   - parameters: 字典参数
    ///   - name: 接受上传数据的服务器字段
    ///   - data: 要上传的二进制
    ///   - completion: 完成回调
    func upload(URLString:String,parameters:[String:Any]?,name:String,data:Data,completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()) {
        
        post(URLString, parameters: parameters, constructingBodyWith: { (formData) in
            // FIXME : 创建formData
            formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
        }, progress: nil, success: { (_, json) in
            // 完成回调
            completion(json, true)
          
        }) { (task, error) in
            //针对token过期的处理方法
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                //  FIXME: 处理token 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: JCLUserShouldLoginNotification), object: "bad token")
            }
            print("网络请求错误\(error)")
            completion(nil, false)
            
        }
        
    }
    
    ///用一个方法封装AFN的GET/POST方法
    ///
    /// - Parameters:
    ///   - method: GET/POST
    ///   - URLString: urlSting
    ///   - parameters: 字典参数
    ///   - completion: 回调/成功、失败
    func request(method: JCLNetMethod = .GET ,URLString: String , parameters:[String: Any],completion:@escaping (_ json: Any?,_ isSuccess: Bool)->()) {
        
        
        /// 定义成功回调闭包
        let success = { (task: URLSessionDataTask,json: Any?)->() in
            completion(json as AnyObject?,true)
        
        }
        
        let failure = {(task:URLSessionDataTask?,error:NSError)->() in

            
            //针对token过期的处理方法
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                //  FIXME: 处理token 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: JCLUserShouldLoginNotification), object: nil)
            }
           completion(nil, false)
        }
       
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure as? (URLSessionDataTask?, Error) -> Void )
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure as? (URLSessionDataTask?, Error) -> Void)
        }
        
    }
    
}
